﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BySoft.Server.Common.Entity;
using BySoft.Server.Business;
using OneSoft.EntityCore;
using System.Reflection;
using System.Data;
using System.Configuration;
using BySoft.Web.Utility;
using BySoft.Server.Common.Schema;
using BySoft.Server.Common.Enum;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using BySoft.Server.Common;

namespace BySoft.Web.Site
{
    public class BasePage : System.Web.UI.Page
    {
        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "button", "showbutton();", true);
        }

        /// <summary>
        /// 检查登录
        /// </summary>
        /// <returns></returns>
        protected bool CheckLogin()
        {

            if (Session["Login_User"] == null)
            {
                //Session["Login_User"] = SysUser.GetSysUserByID("Admin"); //临时数据
                //return true;
                return false;
            }
            else
            {
                //Session["Login_User"] = SysUser.GetSysUserByID("Admin"); //临时数据
                return true;
            }
        }
        /// <summary>
        /// 当前登陆用户
        /// </summary>
        public SysUserEntity CurrentUser
        {
            get
            {

                SysUserEntity enUser = new SysUserEntity();
                if (Session["Login_User"] != null)
                {
                    enUser = (SysUserEntity)Session["Login_User"];
                }
                else
                {
                    //enUser.Userid = "Test";
                    //enUser.Username = "Test";
                }
                return enUser;
            }
        }

        protected void ClearSession(List<string> lst)
        {
            for (int i = 0; i < Session.Count; i++)
            {
                string str = Session.Keys[i];
                if (!lst.Contains(str))
                {
                    Session.Remove(str);
                }
            }
        }

        protected List<string> GetSession()
        {
            List<string> lst = new List<string>();
            lst.Add("Login_User");
            lst.Add("TopModulelist");
            lst.Add("LeftModulelist");
            return lst;
        }

        protected void InitCheck(GridView grdCheck,string strTbl, string strCode)
        {
            DataTable dt = ClsComm.SelectCheck("BS_OutGood", strCode);
            dt.Columns.Add("IsSuccessName");
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    item["IsSuccessName"] = CommonMethod.GetString(item["IsSuccess"]).Equals("1") ? "是" : "否";
                }
            }
            if (dt.Rows.Count > 0)
            {
                grdCheck.DataSource = dt;
                grdCheck.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdCheck, dt);
            }
            UIHelper.RunScript(this.Page, "iframeAutoFit();");
        }

        protected void BindStock(DropDownList ddl)
        {
            //DataTable dtProcessDetail = MdStock.SelectHead("");
            //DataRow row = dtProcessDetail.NewRow();
            //row["StockID"] = "";
            //row["StockName"] = "...请选择";
            //dtProcessDetail.Rows.InsertAt(row, 0);

            //ddl.DataSource = dtProcessDetail;
            //ddl.DataValueField = "StockID";
            //ddl.DataTextField = "StockName";
            //ddl.DataBind();
        }

        protected void BindUser(DropDownList ddl)
        {
            DataTable dt = SysUser.Select();
            DataRow row = dt.NewRow();
            row["UserID"] = "";
            row["UserName"] = "...请选择";
            dt.Rows.InsertAt(row, 0);

            ddl.DataSource = dt;
            ddl.DataValueField = "UserID";
            ddl.DataTextField = "UserName";
            ddl.DataBind();
        }

        protected void BindDepart(DropDownList ddl)
        {
            //DataTable dtProcessDetail = MdManudepart.SelectHead("");
            //DataRow row = dtProcessDetail.NewRow();
            //row["ManuDepartID"] = "";
            //row["ManuDepartName"] = "...请选择";
            //dtProcessDetail.Rows.InsertAt(row, 0);

            //ddl.DataSource = dtProcessDetail;
            //ddl.DataValueField = "ManuDepartID";
            //ddl.DataTextField = "ManuDepartName";
            //ddl.DataBind();
        }

        protected void BindMatType(DropDownList ddl,bool bHaveEpt)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("mc");

            DataRow row = null;
            if (bHaveEpt)
            {
                row = dt.NewRow();
                row["id"] = "";
                row["mc"] = "...请选择";
                dt.Rows.Add(row);
            }

            row = dt.NewRow();
            row["id"] = "1";
            row["mc"] = "铝材";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "2";
            row["mc"] = "钢材";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "3";
            row["mc"] = "玻璃";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "4";
            row["mc"] = "石材";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "5";
            row["mc"] = "其他材料";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "6";
            row["mc"] = "铝单板";
            dt.Rows.Add(row);

            ddl.DataSource = dt;
            ddl.DataValueField = "id";
            ddl.DataTextField = "mc";
            ddl.DataBind();
        }

        protected void BindMaster(DropDownList ddl)
        {
            DataTable dt = GetMaster();
            ddl.DataSource = dt;
            ddl.DataValueField = "UserID";
            ddl.DataTextField = "UserName";
            ddl.DataBind();
        }

        protected DataTable GetMaster()
        {
            DataTable dt = SysUser.Select();
            DataRow row = dt.NewRow();
            row["UserID"] = "";
            row["UserName"] = "...请选择";
            dt.Rows.InsertAt(row, 0);
            return dt;
        }

        protected DataTable BindManuProcess()
        {
            DataTable dt = SelectionCatche.GetParametersByType("ManuProcess");
            DataRow dr = dt.NewRow();
            dr["ParameterCode"] = "";
            dr["ParameterName"] = "请选择...";
            dt.Rows.InsertAt(dr, 0);
            return dt;
        }

        protected void BindManuProcess(DropDownList ddl)
        {
            DataTable dt = BindManuProcess();
            ddl.DataSource = dt;
            ddl.DataValueField = "ParameterCode";
            ddl.DataTextField = "ParameterName";
            ddl.DataBind();
        }

        protected DataTable BindManuDepart()
        {
            //DataTable dtProcessDetail = MdManudepart.SelectHead("");
            //DataRow row = dtProcessDetail.NewRow();
            //row["ManuDepartID"] = "";
            //row["ManuDepartName"] = "...请选择";
            //dtProcessDetail.Rows.InsertAt(row, 0);
            //return dtProcessDetail;
            return new DataTable();
        }

        protected void BindManuDepart(DropDownList ddl)
        {
            DataTable dt = BindManuDepart();
            ddl.DataSource = dt;
            ddl.DataValueField = "ManuDepartID";
            ddl.DataTextField = "ManuDepartName";
            ddl.DataBind();
        }

        protected DataTable BindExportType()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("mc");

            DataRow row = dt.NewRow();
            row["id"] = "1";
            row["mc"] = "预算单";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "2";
            row["mc"] = "请购单";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "3";
            row["mc"] = "采购单";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "4";
            row["mc"] = "收货单";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "5";
            row["mc"] = "发货单";
            dt.Rows.Add(row);

            return dt;
        }

        /// <summary>
        /// 当前登录厂区
        /// </summary>
        public string FactoryType
        {
            get
            {
                string strLogin_FactoryType = "";
                if (Session["Login_FactoryType"] != null)
                {
                    strLogin_FactoryType = (string)Session["Login_FactoryType"];
                }
                return strLogin_FactoryType;
            }
        }

        public List<SysRoleEntity> CurrentUserRole
        {
            get
            {
                return SysRole.GetByCondition("where RoleID IN (SELECT sur.RoleID FROM SYS_UserRole sur WHERE sur.UserID='" + CurrentUser.UserID + "' )");
            }
        }

        public void AddLoginFactoryType(string strLogin_FactoryType)
        {
            Session["Login_FactoryType"] = strLogin_FactoryType;
        }

        public void AddLoginUser(SysUserEntity oSysUser)
        {
            Session["Login_User"] = oSysUser;
        }


        public static EntityCollection<T> ConvertDataTableToEntity<T>(DataTable dt)
           where T : EntityBase, new()
        {
            EntityCollection<T> result = new EntityCollection<T>();
            T t;
            PropertyInfo[] propertyInfo;

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    t = new T();
                    propertyInfo = t.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
                    foreach (DataColumn column in dt.Columns)
                    {
                        //if (t.ContainsKey(column.ColumnName))
                        //{
                        //    t.SetData(column.ColumnName, row[column]);
                        //}

                        for (int i = 0, j = propertyInfo.Length; i < j; i++)
                        {
                            PropertyInfo pi = propertyInfo[i];
                            if (pi.Name.ToLower() != column.ColumnName.ToLower())
                            {
                                continue;
                            }
                            else
                            {
                                pi.SetValue(t, row[column].ToString(), null);
                            }

                        }

                    }
                    result.Add(t);
                }
            }
            return result;
        }


        /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <param name="ActionType">动作类型</param>
        /// <param name="Key">操作数据关键字</param>
        /// <param name="IsSuccess">是否成功</param>
        /// <param name="Exception">异常信息</param>
        /// <param name="Entities">数据</param>
        protected void LogAction(BaseEnum.ActionType ActionType, string Key, bool IsSuccess, Exception Exception, params EntityBase[] Entities)
        {
            LogAction(ActionType, Key, IsSuccess, Exception, true, Entities);
        }


        protected void LogAction(BaseEnum.ActionType ActionType, string Key, bool IsSuccess, Exception Exception, bool bCheckModule, params EntityBase[] Entities)
        {
            if (ConfigurationManager.AppSettings["OperationLog_Enable"] == "1")
            {

                SysUseroperationlogEntity operationLogEntity = new SysUseroperationlogEntity();

                operationLogEntity.TheKey = Key;

                operationLogEntity.ActionType = ((int)ActionType).ToString();

                if (Exception != null)
                {
                    operationLogEntity.ExceptionMsg = "Message:\r\n" + Exception.Message + "\r\nStackTrace:\r\n+" + Exception.StackTrace + "\r\nSource:\r\n" + Exception.Source;
                }
                operationLogEntity.LogTime = DateTime.Now;
                operationLogEntity.IPAddress = Request.UserHostAddress;
                operationLogEntity.ActionResult = IsSuccess ? "1" : "0";
                operationLogEntity.UserID = CurrentUser.UserID;
                operationLogEntity.UserName = CurrentUser.UserName;


                operationLogEntity.DataXML = "";

                foreach (EntityBase entity in Entities)
                {

                    operationLogEntity.DataXML += SerializeHelper.SerializeObjectToString(entity);

                    operationLogEntity.DataXML += "\r\n\r\n";

                }
                if (!bCheckModule)
                {
                    SysModuleEntity enModule = SysModule.GetLeftModuleInfoByUrl(Request.Url.ToString());
                    if (!string.IsNullOrEmpty(enModule.ModuleID))
                    {
                        operationLogEntity.ModuleID = enModule.ModuleID;
                        operationLogEntity.ModuleName = enModule.ModuleName;
                    }
                }
                SysUseroperationlog.InsertSysUseroperationlog(operationLogEntity);
            }
        }

        /// <summary>
        ///   时间格式化成（yyyy-MM-dd）格式的字符串，时间为1900-1-1 返""
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public string FomatDateTime(DateTime? date)
        {
            if (date == null || date.Value.ToString("yyyy-MM-dd") == "1900-01-01")
                return "";
            else return date.Value.ToString(SystemConfig.DateFromat);
        }

        #region 绑定参数配置的参数
        /// <summary>
        ///  为ListControl类型控件绑定配置参数，如（DropDownList,CheckBoxList等）
        /// </summary>
        /// <param name="parameterTypeID">参数类别</param>
        /// <param name="control">控件ID</param>
        public void BindParameterForListControl(string parameterTypeID, ListControl control)
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParametersByType(parameterTypeID);
            control.DataSource = dt;
            control.DataTextField = SysParameterTable.C_PARAMETERNAME;//"PARAMETERNAME"; 
            control.DataValueField = SysParameterTable.C_PARAMETERCODE;// "C_PARAMETERCODE";
            control.DataBind();
        }

        public void BindParameterForListControlInsFir(string parameterTypeID, DropDownList control)
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParametersByType(parameterTypeID);
            control.DataSource = dt;
            control.DataTextField = SysParameterTable.C_PARAMETERNAME;//"PARAMETERNAME"; 
            control.DataValueField = SysParameterTable.C_PARAMETERCODE;// "C_PARAMETERCODE";
            control.DataBind();
            UIHelper.InsertFirstItem(control);
        }

        public void BindParameterForListControlByCondition(string parameterTypeID, ListControl control, string strCondition)
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParametersByType(parameterTypeID);
            DataView dv = dt.DefaultView;
            dv.RowFilter = strCondition;
            control.DataSource = dv;
            control.DataTextField = SysParameterTable.C_PARAMETERNAME;//"PARAMETERNAME"; 
            control.DataValueField = SysParameterTable.C_PARAMETERCODE;// "C_PARAMETERCODE";
            control.DataBind();
        }

        public void BindParameterValueForListControl(string parameterTypeID, ListControl control)
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParametersByType(parameterTypeID);
            control.DataSource = dt;
            control.DataTextField = SysParameterTable.C_PARAMETERNAME;//"PARAMETERNAME"; 
            control.DataValueField = SysParameterTable.C_PARATMETERVALUE;// "C_PARAMETERCODE";
            control.DataBind();
        }
        /// <summary>
        ///  为ListControl类型控件绑定配置参数，如（DropDownList,CheckBoxList等）
        /// </summary>
        /// <param name="parameterTypeID">参数类别</param>
        /// <param name="parameterValue">参数Value值</param>
        /// <param name="control">控件ID</param>
        public void BindParameterForListControl(string parameterTypeID, string parameterValue, ListControl control)
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParametersByType(parameterTypeID);
            DataView dv = dt.DefaultView;
            dv.RowFilter = SysParameterTable.C_PARATMETERVALUE + "='" + parameterValue + "'";
            control.DataSource = dv;
            control.DataTextField = SysParameterTable.C_PARAMETERNAME;
            control.DataValueField = SysParameterTable.C_PARAMETERCODE;
            control.DataBind();
        }

        public void BindParameterForListControlRequistStatus(string parameterTypeID, ListControl control)
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParametersByType(parameterTypeID);
            DataView dv = dt.DefaultView;
            dv.RowFilter = SysParameterTable.C_PARAMETERCODE + "='03'";
            control.DataSource = dv;
            control.DataTextField = SysParameterTable.C_PARAMETERNAME;
            control.DataValueField = SysParameterTable.C_PARAMETERCODE;
            control.DataBind();
        }

        public void BindParameterForListControlRequistNoStatus(string parameterTypeID, ListControl control)
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParametersByType(parameterTypeID);
            DataView dv = dt.DefaultView;
            dv.RowFilter = SysParameterTable.C_PARAMETERCODE + "<>'03'";
            control.DataSource = dv;
            control.DataTextField = SysParameterTable.C_PARAMETERNAME;
            control.DataValueField = SysParameterTable.C_PARAMETERCODE;
            control.DataBind();
        }
        #endregion

        #region 绑定GridView里的AutoCompelet
        /// <summary>
        /// 绑定gridview里的AutoCompelet
        /// </summary>
        /// <param name="gv">girdview</param>
        /// <param name="txtTestId">要绑定显示的textbox的id</param>
        /// <param name="txtValueId">要绑定值的textbox的id</param>
        protected void BindGridViewAutoComplete(GridView gv, string txtTestId, string txtValueId)
        {
            string script = string.Empty;
            foreach (GridViewRow row in gv.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    if (row.FindControl(txtTestId) != null && row.FindControl(txtValueId) != null)
                    {
                        TextBox tbtext = row.FindControl(txtTestId) as TextBox;
                        TextBox tbvalue = row.FindControl(txtValueId) as TextBox;
                        script += "AutoCompleteBox('" + tbtext.ClientID + "', '" + tbvalue.ClientID + "', '1');";
                    }
                }
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", script, true);
        }

        //protected void BindGridViewAutoComplete2(GridView gv, string tbString, string Type)
        //{
        //    string script = string.Empty;
        //    foreach (GridViewRow row in gv.Rows)
        //    {
        //        if (row.RowType == DataControlRowType.DataRow)
        //        {
        //            if (row.FindControl(tbString) != null)
        //            {
        //                SuggestTextBox2 tbs = row.FindControl(tbString) as SuggestTextBox2;
        //                string tb = tbs.ClientID;
        //                script += "AutoCompleteBox('" + tb + "_txtName" + "', '" + tb + "_hidValue" + "', '" + Type + "');";
        //            }
        //        }
        //    }
        //    ScriptManager.RegisterStartupScript(this, this.GetType(), "", script, true);
        //}
        #endregion

        public void EnableGridViewRow(OneSoft.Web.UI.WebControls.SGridView sgv, DataTable dt, string strCompareField, bool bEnable)
        {
            if (null == dt || dt.Rows.Count < 1)
            {
                return;
            }
            DataTable dtTemp = dt.Copy();
            foreach (DataRow dr in dtTemp.Rows)
            {
                foreach (GridViewRow gr in sgv.Rows)
                {
                    Label lblCompareField = gr.FindControl("lbl" + strCompareField) as Label;
                    if (lblCompareField.Text.Trim().Equals(dr[strCompareField].ToString().Trim()))
                    {
                        if (gr.FindControl("cbChoose") != null)
                            ((CheckBox)gr.FindControl("cbChoose")).Checked = true;
                        if (bEnable)
                            gr.Enabled = false;
                        break;
                    }
                }
            }
        }

        public void EnableGridViewRow(OneSoft.Web.UI.WebControls.SGridView sgv, DataTable dt, string strCompareField1, string strCompareField2, bool bEnable)
        {
            if (null == dt || dt.Rows.Count < 1)
            {
                return;
            }
            DataTable dtTemp = dt.Copy();
            foreach (DataRow dr in dtTemp.Rows)
            {
                foreach (GridViewRow gr in sgv.Rows)
                {
                    Label lblCompareField1 = gr.FindControl("lbl" + strCompareField1) as Label;
                    Label lblCompareField2 = gr.FindControl("lbl" + strCompareField2) as Label;
                    if (lblCompareField1.Text.Trim().Equals(dr[strCompareField1].ToString().Trim()) &&
                        lblCompareField2.Text.Trim().Equals(dr[strCompareField2].ToString().Trim()))
                    {
                        if (gr.FindControl("cbChoose") != null)
                            ((CheckBox)gr.FindControl("cbChoose")).Checked = true;
                        if (bEnable)
                            gr.Enabled = false;
                        break;
                    }
                }
            }
        }

        /// <summary>
        ///   err string格式化 去除"\r \n"
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public string FomatString(string str)
        {
            if (str == null || str == "")
                return "";
            else return str.ToString().Replace("\r", "").Replace("\n", "").Trim();
        }

        protected DateTime? GetDateTime(HtmlInputText tb)
        {
            if (string.IsNullOrEmpty(tb.Value))
            {
                return null;
            }
            else
            {
                return Convert.ToDateTime(tb.Value);
            }
        }

        protected DateTime? GetDateTime(Label obj)
        {
            if (string.IsNullOrEmpty(obj.Text))
            {
                return null;
            }
            else
            {
                return Convert.ToDateTime(obj.Text);
            }
        }

        protected DateTime? GetDateTimeHour(HtmlInputText tb)
        {
            if (string.IsNullOrEmpty(tb.Value))
            {
                return null;
            }
            else
            {
                return Convert.ToDateTime(tb.Value + ":00:00");
            }
        }

        protected decimal? GetDecimal(Label tb)
        {
            if (string.IsNullOrEmpty(tb.Text.Trim()))
            {
                return null;
            }
            else
            {
                return Convert.ToDecimal(tb.Text.Trim());
            }
        }

        protected decimal? GetDecimal(object obj)
        {
            if (null == obj)
            {
                return null;
            }
            else
            {
                return Convert.ToDecimal(obj.ToString());
            }
        }

        protected decimal? GetDecimal(HiddenField obj)
        {
            if (string.IsNullOrEmpty(obj.Value))
            {
                return null;
            }
            else
            {
                return Convert.ToDecimal(obj.Value);
            }
        }

        protected decimal? GetDecimal(TextBox tb)
        {
            if (string.IsNullOrEmpty(tb.Text.Trim()))
            {
                return null;
            }
            else
            {
                return Convert.ToDecimal(tb.Text.Trim());
            }
        }

        protected String GetString(HiddenField obj)
        {
            if (string.IsNullOrEmpty(obj.Value))
            {
                return null;
            }
            else
            {
                return obj.Value;
            }
        }

        protected String GetString(CheckBox obj)
        {
            return obj.Checked ? "1" : "0";
        }

        protected String GetString(TextBox obj)
        {
            if (string.IsNullOrEmpty(obj.Text.Trim()))
            {
                return null;
            }
            else
            {
                return obj.Text.Trim();
            }
        }

        protected String GetString(DropDownList obj)
        {
            if (string.IsNullOrEmpty(obj.SelectedValue))
            {
                return null;
            }
            else
            {
                return obj.SelectedValue;
            }
        }

        protected String GetString(Label obj)
        {
            if (string.IsNullOrEmpty(obj.Text.Trim()))
            {
                return null;
            }
            else
            {
                return obj.Text.Trim();
            }
        }

        protected Int32? GetInt(object obj)
        {
            if (null == obj)
            {
                return null;
            }
            else
            {
                return Convert.ToInt32(obj.ToString().Trim());
            }
        }

        protected Int32? GetInt(TextBox tb)
        {
            if (string.IsNullOrEmpty(tb.Text.Trim()))
            {
                return null;
            }
            else
            {
                return Convert.ToInt32(tb.Text.Trim());
            }
        }

        protected Int32? GetInt(Label tb)
        {
            if (string.IsNullOrEmpty(tb.Text.Trim()))
            {
                return null;
            }
            else
            {
                return Convert.ToInt32(tb.Text.Trim());
            }
        }

        protected decimal? GetDecimal(DropDownList ddl)
        {
            if (string.IsNullOrEmpty(ddl.SelectedValue))
            {
                return null;
            }
            else
            {
                return Convert.ToDecimal(ddl.SelectedValue);
            }
        }

        protected Int32? GetInt(DropDownList ddl)
        {
            if (string.IsNullOrEmpty(ddl.SelectedValue))
            {
                return null;
            }
            else
            {
                return Convert.ToInt32(ddl.SelectedValue);
            }
        }

        protected String GetGridViewString(string obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.ToString().Trim()))
            {
                return String.Empty;
            }
            else
            {
                return obj.Replace("&nbsp;", "");
            }
        }

        protected String GetGridViewString(HtmlInputText obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.Value))
            {
                return String.Empty;
            }
            else
            {
                return obj.Value;
            }
        }

        protected String GetGridViewString(Label obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.Text.Trim()))
            {
                return String.Empty;
            }
            else
            {
                return obj.Text.Replace("&nbsp;", "");
            }
        }

        protected String GetGridViewString(DropDownList obj)
        {
            if (obj == null)
            {
                return "";
            }
            else
            {
                return obj.SelectedValue;
            }
        }

        protected Int32? GetGridViewInt(TextBox obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.Text))
            {
                return null;
            }
            else
            {
                string str = obj.Text.Replace("&nbsp;", "");
                return Convert.ToInt32(str);
            }
        }

        protected Int32? GetGridViewInt(Label obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.Text))
            {
                return null;
            }
            else
            {
                string str = obj.Text.Replace("&nbsp;", "");
                return Convert.ToInt32(str);
            }
        }

        protected Decimal? GetGridViewDecimal(TextBox obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.Text))
            {
                return null;
            }
            else
            {
                string str = obj.Text.Replace("&nbsp;", "");
                return Convert.ToDecimal(str);
            }
        }

        protected Decimal? GetGridViewDecimal(Label obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.Text))
            {
                return null;
            }
            else
            {
                string str = obj.Text.Replace("&nbsp;", "");
                return Convert.ToDecimal(str);
            }
        }

        protected string GetGridViewString(TextBox obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.Text))
            {
                return "";
            }
            else
            {
                return obj.Text.Replace("&nbsp;", "");
            }
        }

        protected string GetGridViewString(HiddenField obj)
        {
            if (obj == null ||
                string.IsNullOrEmpty(obj.Value))
            {
                return "";
            }
            else
            {
                return obj.Value.Replace("&nbsp;", "");
            }
        }

        protected string GetPlanProcessRdo(RadioButtonList rbl)
        {
            foreach (ListItem item in rbl.Items)
            {
                if (item.Selected == true)
                {
                    return item.Value;
                }
            }
            return "";
        }

        protected void SetRadioButtonList(RadioButtonList rbl, string strValue)
        {
            foreach (ListItem item in rbl.Items)
            {
                if (item.Value == strValue)
                {
                    item.Selected = true;
                    break;
                }
            }
        }

        protected void SetCheckBoxList(DataTable dt, string strKey, CheckBoxList cbl)
        {
            DataView dv = new DataView(dt);
            dv.RowFilter = "SelType='" + strKey + "'";
            DataTable dtTemp = dv.ToTable();
            if (dtTemp != null && dtTemp.Rows.Count > 0)
            {
                foreach (DataRow drItem in dtTemp.Rows)
                {
                    foreach (ListItem cblItem in cbl.Items)
                    {
                        if (cblItem.Value == drItem["SelValue"].ToString().Trim())
                        {
                            cblItem.Selected = true;
                            break;
                        }
                    }
                }
            }
        }


        protected DataTable CreateDTFile()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("AttachmentID");
            dt.Columns.Add("FileType");
            dt.Columns.Add("FileSize");
            dt.Columns.Add("UpDateTime");
            dt.Columns.Add("FileURL");
            dt.Columns.Add("FileName");
            dt.Columns.Add("FormType");
            dt.Columns.Add("FormID");
            dt.Columns.Add("Status");
            return dt;
        }

        protected void BindListData(ListBox lstFile, DataTable dt)
        {
            lstFile.DataSource = dt;
            lstFile.DataTextField = "FileName";
            lstFile.DataValueField = "AttachmentID";
            lstFile.DataBind();
        }

        protected void BindListDataOne(Label lbl, DataTable dt)
        {
            lbl.Text = "";
            if (dt == null || dt.Rows.Count < 1)
            {
                return;
            }
            DataRow row = dt.Rows[0];
            lbl.Text = CommonMethod.GetString(row["FileName"]);
        }

        protected void DelUpFile(ListBox lstFile,DataTable dt)
        {
            try
            {
                if (!string.IsNullOrEmpty(lstFile.SelectedValue))
                {
                    int i = lstFile.SelectedIndex;
                    lstFile.Items.RemoveAt(i);
                    dt.Rows.RemoveAt(i);
                }
                else { UIHelper.AlertMessage(this.Page, "请选择删除附件！"); }
            }
            catch (Exception ex) { UIHelper.Alert(this.Page, FomatString(ex.Message.ToString())); }
        }
        protected void GetListAdd(DataTable dt, string strBillCode, string strBillType, List<MdAttachmentEntity> lstyFile)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow drItem in dt.Rows)
                {
                    MdAttachmentEntity Detailentity = new MdAttachmentEntity();
                    Detailentity.AttachmentID = Guid.NewGuid().ToString();
                    Detailentity.FileType = BySoft.Server.Common.CommonMethod.GetString(drItem["FileType"]);
                    Detailentity.FileSize = Convert.ToInt32(drItem["FileSize"]);
                    Detailentity.UpDateTime = DateTime.Now;
                    Detailentity.FileURL = BySoft.Server.Common.CommonMethod.GetString(drItem["FileURL"]);
                    Detailentity.FileName = BySoft.Server.Common.CommonMethod.GetString(drItem["FileName"]);
                    Detailentity.FormType = strBillType;
                    Detailentity.FormID = strBillCode;
                    Detailentity.Status = "1";
                    lstyFile.Add(Detailentity);
                }
            }
        }



        public void BindParameterForDDL(string parameterTypeID, DropDownList control)
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParametersByType(parameterTypeID);
            control.DataSource = dt;
            control.DataTextField = SysParameterTable.C_PARAMETERNAME;//"PARAMETERNAME"; 
            control.DataValueField = SysParameterTable.C_PARAMETERCODE;// "C_PARAMETERCODE";
            control.DataBind();
            UIHelper.InsertFirstItem(control);
        }

        /// <summary>
        /// 根据索引和pagesize返回记录
        /// </summary>
        /// <param name="dtProcessDetail">记录集 DataTable</param>
        /// <param name="PageIndex">当前页</param>
        /// <param name="pagesize">一页的记录数</param>
        /// <returns></returns>
        public static DataTable SplitDataTable(DataTable dt, int PageIndex, string strSortKey, int PageSize)
        {
            DataView dv = new DataView(dt);
            dv.Sort = strSortKey;
            dt = dv.ToTable();
            if (PageSize <= 0)
            {
                PageSize = 10;
                if (System.Web.Configuration.WebConfigurationManager.AppSettings["PageSize"] != null &&
                            System.Web.Configuration.WebConfigurationManager.AppSettings["PageSize"].ToString() != "")
                {
                    try
                    {
                        //从web.config读取分页大小
                        PageSize = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.AppSettings["PageSize"].ToString());
                    }
                    catch
                    {
                    }
                }

            }

            if (PageIndex == 0)
                return dt;
            DataTable newdt = dt.Clone();
            //newdt.Clear();
            int rowbegin = (PageIndex - 1) * PageSize;
            int rowend = PageIndex * PageSize;

            if (rowbegin >= dt.Rows.Count)
                return newdt;

            if (rowend > dt.Rows.Count)
                rowend = dt.Rows.Count;
            for (int i = rowbegin; i <= rowend - 1; i++)
            {
                DataRow newdr = newdt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newdr[column.ColumnName] = dr[column.ColumnName];
                }
                newdt.Rows.Add(newdr);
            }

            return newdt;
        }

    }
}
